//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <ddk.h>
#include <bulverde.h>
#include <drvpub.h>
#include "display_def.h"

void BackLight_Open(DisplayContext *pCxt)
{
    GPDR0   = (GPDR0   | (0x1 << 16));

    GPSR0 |=0x00010000;

    //GAFR0_U = GAFR0_U & (~0x3);
    Gpio_SetAFR(16, GPIO_AS_AF2);

    // enable PWM0
    PWMPCR0 = 0x3FF;
    CKEN |= CKEN0_PWM0;
}

//
// Put GPIO 16 to low level will shut off LCD Backlight
//
void BackLight_Close(DisplayContext *pCxt)
{
    // backlight_brightness = lcdctrl_get_brightness( );
    GPDR0   = (GPDR0   | (0x1 << 16));
    // GAFR0_U = (GAFR0_U & ~(0x3 << 0));
    GPCR0   = (1 << 16);

    // disable PWM0
    CKEN &= ~CKEN0_PWM0;
}

//
//  LCD Brightness table
//
int nBrightTable[11][2]={
    {30,  30},  //0
    {50,  30},  //1
    {80,  30},  //2
    {120, 30},  //3
    {185, 30},  //4
    {250, 30},  //5 default
    {315, 30},  //6
    {380, 40},  //7
    {420, 40},  //8
    {460, 40},  //9
    {500, 50},  //10
};

int brightness_level = 5;

int BackLight_SetBrightness(DisplayContext *pCxt, int b)
{
    // validate the arguments
    if (b < 0 || b > 10) {
        return -1;
    }

    // cprintf("Set Brightness = %d.\n", b);

    // look up the table
    brightness_level = b;
    PWMDCR0 = nBrightTable[brightness_level][0];
    return 0;
}

void SetBrightnessOn()
{
    PWMDCR0 = nBrightTable[brightness_level][0];
    //cprintf("brightness %d",PWMDCR0);
}

void SetBrightnessLow()
{
    PWMDCR0 = nBrightTable[brightness_level][1];
    //cprintf("brightness %d",PWMDCR0);
}
